package interface_layer;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import processing_layer.CourseSession;
import processing_layer.XSLTHandler;

import database_layer.Common;
import database_layer.QueryDispatcher;

/**
 * This servlet is a part of the process of working the XSLT advanced feature.
 * It is used to retrieve the XML file, before transforming it with XSLT.
 * This servlet is invoked by the corresponding code in the javascript, and then
 * the timetable is produced.
 */
public class StudentTimetable extends HttpServlet
{
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public StudentTimetable()
    {
        super();
    }

    
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) 
	{
		try
		{
			String username = (String) request.getSession().getAttribute("username");
			
			if (null == username)
			{
				ErrorHandler.parseForErrors(Common.UNAUTHORIZED_OPERATION, response, null);
				return;
			}
			
			try
			{
				response.setContentType("text/xml");
				PrintWriter output = response.getWriter();
				
				ArrayList<CourseSession> sessions = QueryDispatcher.getRegisteredSessions(username);
				if (null == sessions || 0 == sessions.size())
				{
					ErrorHandler.parseForErrors(Common.INTERNAL_DB_ERROR, response, null);
					return;
				}
				StringWriter XMLOutput = XSLTHandler.generateSessionsXML(sessions);
				output.print(XMLOutput);
			}
			catch (Exception e)
			{
				ErrorHandler.parseForErrors(Common.INTERNAL_DB_ERROR, response, null);
			}
		}
		catch (Exception e)
		{
			System.out.println("Exception is : " + e.getLocalizedMessage());
			ErrorHandler.parseForErrors(Common.INTERNAL_ERROR, response, null);
		}
	}


	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
	{
		doPost(req, resp);
	}

}
